// pages/new_book/new_book.js
import Toast from '@vant/weapp/toast/toast';

const buildings = {
  教学楼: ['9栋', '10栋', '11栋', '15栋', '16栋'],
  宿舍楼: ['14栋', '22栋', '23栋', '25栋', '26栋'],
};
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ISBN: '',
    bookName: '',   // 图书名称
    version: '',    // 图书版本
    author: '',     // 图书作者
    publish: '',    // 出版社
    amount: 0,        // 单价
    num: 0,           // 上架数量
    location: null,   // 所在楼栋
    imgList: [],      // 展示图片列表
    showLocation: false,
    columns: [
      {
        values: Object.keys(buildings),
        className: 'column1',
      },
      {
        values: buildings['教学楼'],
        className: 'column2',
        defaultIndex: 2,
      },
    ],
  },
  // 显示/隐藏 所在楼栋选择弹出层
  changeShowLocation: function () {
    let that = this
    this.setData({ showLocation: !that.data.showLocation })
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    let obj = {
      area: value[0],
      building: value[1]
    }
    picker.setColumnValues(1, buildings[obj.area]);
  },
  selectLocation(event) {
    const { value, index } = event.detail;
    let obj = {
      area: {
        id: index[0],
        name: value[0]
      },
      building: {
        id: index[1],
        name: value[1]
      }
    }
    console.log(`选择的楼栋 = ${obj}`);
    this.setData({
      location: obj
    })
    console.log(this.data.location.area.name + this.data.location.building.name);
    this.changeShowLocation()
  },
  // 点击input框右侧?按钮，显示提示
  onClickIcon(event) {
    console.log(event);
    const dataHelp = event.currentTarget.dataset.help
    if (dataHelp === 'ISBN') {
      wx.showToast({
        title: '例如：9787115480170',
        icon: 'none'
      })
    } else if (dataHelp === 'bookName') {
      wx.showToast({
        title: '例如：JavaScript高级程序设计',
        icon: 'none'
      })
    } else if (dataHelp === 'version') {
      wx.showToast({
        title: '例如：第X版',
        icon: 'none'
      })
    } else if (dataHelp === 'author') {
      wx.showToast({
        title: '请输入作者姓名',
        icon: 'none'
      })
    } else if (dataHelp === 'publish') {
      wx.showToast({
        title: '例如：清华出版社',
        icon: 'none'
      })
    } else if (dataHelp === 'num') {
      wx.showToast({
        title: '请输入数字',
        icon: 'none'
      })
    } else if (dataHelp === 'amount') {
      wx.showToast({
        title: '请输入单价，仅支持人民币',
        icon: 'none'
      })
    }
  },
  // 输入框失焦检测数据是否可用
  checkBookInfo(event) {
    console.log('detail = ', event.detail);
    const dataHelp = event.currentTarget.dataset.help
    // 检测ISBN
    if (dataHelp === 'ISBN') {
      if (event.detail.value.length !== 13) {
        wx.showToast({
          title: 'ISBN为13位数字',
          icon: 'error'
        })
      } else {
        this.setData({
          ISBN: event.detail.value
        })
      }
    } else if (dataHelp === 'bookName') {
      // 图书名称
      this.setData({
        bookName: event.detail.value
      })
    } else if (dataHelp === 'version') {
      // 版本号
      const str = event.detail.value
      // 判断最后一个字符是否为'版'
      if (str[str.length - 1] !== '版') {
        wx.showToast({
          title: '第X版，或XX版',
          icon: 'error'
        })
      } else {
        this.setData({
          version: event.detail.value
        })
      }
    } else if (dataHelp === 'author') {
      this.setData({
        author: event.detail.value
      })
    } else if (dataHelp === 'publish') {
      // 出版社
      if (event.detail.value.slice(-3) !== '出版社') {
        wx.showToast({
          title: 'xxx出版社',
          icon: 'error'
        })
      } else {
        this.setData({
          publish: event.detail.value
        })
      }
    } else if (dataHelp === 'num') {
      if (typeof Number(event.detail.value) !== 'number') {
        wx.showToast({
          title: '仅支持整数',
          icon: 'error'
        })
      } else {
        this.setData({
          num: Number(event.detail.value)
        })
      }
    } else if (dataHelp === 'amount') {
      if (typeof Number(event.detail.value) !== 'number') {
        wx.showToast({
          title: '可输入小数',
          icon: 'error'
        })
      } else {
        this.setData({
          amount: Number(event.detail.value)
        })
      }
    }
  },
  // 验证是否可以上架图书, false --> 不可上架; true --> 可上架
  checkSubmit() {
    // 结构赋值，浅拷贝
    const {ISBN, bookName, version, author,
      publish, amount, num, location, imgList} = this.data
    if (ISBN.length !== 13) return false
    if (bookName.length === 0) return false
    if (version.length === 0 || version[version.length - 1] !== '版') return false
    if (author.length === 0) return false
    if (publish.length === 0 || publish.slice(-3) !== '出版社') return false
    if (typeof Number(amount) !== 'number') return false
    if (typeof Number(num) !== 'number') return false
    if (location.length === 0) return false
    return true
  },
  // 上架按钮点击事件
  handleShelves(event) {
    // 结构赋值，浅拷贝
    const {ISBN, bookName, version, author,
      publish, amount, num, location, imgList} = this.data

    // 验证是否可以上架图书
    // false --> return; true --> 继续执行
    if (!this.checkSubmit()) {
      wx.showToast({
        title: '图书信息有误',
        icon: 'error',
        duration: 1500
      })
      return
    }
    // 从缓存中拿用户信息
    const ui = wx.getStorageSync('userinfo')
    wx.showModal({
      title: '上架图书',
      content: '是否上架当前图书？',
      success (res) {
        if (res.confirm) {
          // 调用后台API，删除购物车内订单
          console.log('调用后他API，图书上架，订单状态改为??');
          wx.cloud.callFunction({
            name: 'book_add',
            data: {
              openid: ui.openid,
              ISBN,
              bookName,
              version,
              author,
              publish,
              amount,
              num,
              location,
              imgList
            },
            success: res => {
              console.log('book_add的回调：', res);
              wx.showToast({
                title: '上架成功',
                icon: 'success',
                duration: 1500
              })
            },
            fail: res => {
              console.log('book_add调用失败，错误信息：', res);
              wx.showToast({
                title: '上架失败',
                icon: 'error',
                duration: 1500
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 上传照片
  afterReadImg(e) {
    const { file } = e.detail;
    console.log('上传的图片：', file);
    // 上传完成需要更新 imgList
    const { imgList = [] } = this.data;

    // imgList.push({ ...file, url: res.data });
    Object.assign(file, {deletable: true})
    imgList.push({ ...file });
    this.setData({ imgList });
    console.log('imgList = ', this.data.imgList);
  },
  // 删除上传的照片
  deleteImg() {
    this.setData({imgList: []})
  }
})